﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using BizScore.Model;
using Office;

namespace BizScore
{




    /********************************************************************************************************
     *                                                                                                      *
     *      根据大理市的 笔试分数进行统计                                                                   *    
     *      获得岗位及总分信息                                                                              *
     *      岗位代码：匹配列 Y  "报考职位代码" 进行提取                                                     *
     *      总分：    匹配列 AI "笔试总分（含加分)"                                                         *
     *                                                                                                      *
     *                                                                                                      *
     ********************************************************************************************************
     */





    /// <summary>
    /// 获得最终岗位的实际需要人数
    /// </summary>
    public class GetExamScore
    {
        protected static GetExamScore instance = new GetExamScore();

        /// <summary>
        /// 成绩表excel的目录
        /// </summary>
        protected static string excelPath = null;


        /// <summary>
        /// 成绩表excel的保存目录 
        /// </summary>
        protected static string saveASPath = null;


        /// <summary>
        /// 岗位代码所在列的列号
        /// </summary>
        protected static string _postID = "Y";


        /// <summary>
        /// 科目一所在列的列号
        /// </summary>
        protected static string _subject1 = "";


        /// <summary>
        /// 科目二所在列的列号
        /// </summary>
        protected static string _subject2 = "";


        /// <summary>
        /// 总分所在列的列号
        /// </summary>
        protected static string _total = "AI";

        protected static Dictionary<string, string> dic = new Dictionary<string, string>();

        protected static ExcelSingle excel = new ExcelSingle();


        /// <summary>
        /// 设置要提取的列的列号
        /// </summary>
        /// <param name="postID"></param>
        /// <param name="total"></param>
        public static void SetColumns(string postID, string total)
        {
            //TODO**************************
            _postID = postID;
            _total = total;

            throw new NotImplementedException();
        }


        public static GetExamScore GetInstance(string path,string savePath)
        {
            excelPath = path;
            saveASPath = savePath;
            return instance;
        }

        protected GetExamScore() { }

        protected void GetTitle()
        {
            ExcelRPosition position = new ExcelRPosition();
            
            string val = null;
            dic.Clear();
            object oVal = null;
            while (true)
            {
                oVal = excel.GetData(position.GetCurrentPosition, null);
                if (oVal == null || string.IsNullOrEmpty(oVal.ToString())) break;
                val = oVal.ToString();

                //岗位代码或者职位代码
                if (Regex.IsMatch(val,"职位代码|岗位代码"))
                {
                    _postID = position.CurrentColumn;
                }
                else if(string.IsNullOrEmpty(_postID)&&Regex.IsMatch(val, "报考职位|报考岗位"))
                {
                    _postID = position.CurrentColumn;
                }


                //总分列
                if (Regex.IsMatch(val, "总分"))
                {
                    _total = position.CurrentColumn;
                }
               

                dic.Add(position.GetCurrentPosition, val);
                position.NextCloumns();
            }
        }


        public void OpenExcel()
        {
            excel.OpenExcel(excelPath);
            excel.SaveAsExcelFile(saveASPath, Excel.ExcelVersions.Excel_xls);
            excel.OpenExcelWorksheet("Sheet1");
        }


        public void CloseExcel()
        {
            excel.CloseAllExcel();
        }

        /// <summary>
        /// 异步获得所有的考生信息
        /// </summary>
        /// <returns></returns>
        public async Task<IEnumerable<ExamScore>> GetAllExamineeInfoAsync()
        {
            await Task.Run<List<ExamScore>>(() => {
                return GetAllExamineeInfo().ToList();
            });
            return new ExamScore[0];
        }


        /// <summary>
        /// 获得所有的考生信息
        /// </summary>
        /// <returns></returns>
        public IEnumerable<ExamScore> GetAllExamineeInfo()
        {
            List<ExamScore> list = new List<ExamScore>();

            //打开excel
            //OpenExcel();





            //Y列查找 报考职位
            //AI 列查找 总分
            int index = 2;
            GetTitle();

            ExcelRPosition position = new ExcelRPosition();

            ExcelRPosition pPostID = new ExcelRPosition();
            ExcelRPosition pTotal = new ExcelRPosition();

            pPostID.CurrentColumn = _postID;
            pPostID.CurrentIndex = index;

            pTotal.CurrentColumn = _total;
            pTotal.CurrentIndex = index;

            ExamScore entity = null;
            object oVal = null;

            while (true)
            {
                entity = new ExamScore();
                oVal = excel.GetData(pPostID.GetCurrentPosition, null);
                if (oVal == null|| string.IsNullOrEmpty(oVal.ToString())) break;
                entity.PostID = Regex.Match(oVal.ToString(),"[0-9]+").Value;

                oVal = excel.GetData(pTotal.GetCurrentPosition, null);
                if (oVal == null) oVal = 0f;
                entity.Total = float.Parse(oVal.ToString());
                entity.Index = pPostID.CurrentIndex.ToString();

                position = new ExcelRPosition();
                position.CurrentIndex = pPostID.CurrentIndex;

                int dCount = dic.Count;
                for (int i=0;i<dCount;i++)
                {
                    oVal = excel.GetData(position.GetCurrentPosition, null);
                    if (oVal == null)
                    {
                        oVal = "";
                    }
                    entity.SetDic(position.CurrentColumn, oVal.ToString().Trim());
                    position.NextCloumns();
                }

                entity.ISPassPosition = position.GetCurrentPosition;

                //下一行,下一行
                pPostID.NextRaws();
                pTotal.NextRaws();

                list.Add(entity);
            }

            excel.SaveExcelFile();

            return list;
        }



        /// <summary>
        /// 写入所有的考生信息
        /// </summary>
        /// <returns></returns>
        public void WriteAllExamineeInfo(IEnumerable<ExamScore> list)
        {
          
            //汇总表
            excel.OpenExcelWorksheet("进入面试名单");

            //写入标题
            foreach(var title in dic)
            {
                excel.WriteData(title.Key, null, title.Value);
            }

            //写入数据
            int i = 2;
            foreach (var exam in list)
            {
                foreach(var val in exam.GetDic())
                {
                    excel.WriteData(val.Key+i.ToString(), null, "'"+val.Value);
                    
                }
                i++;
            }


            excel.SaveExcelFile();
            excel.OpenExcelWorksheet("进入面试岗位统计表");

            var values =
                from v in list
                group v by v.PostID into newList
                orderby newList.Key
                select new
                {
                    ID = newList.Key,
                    Count = newList.Count()
                };

            excel.WriteData("A1",null, "岗位代码");
            excel.WriteData("B1", null,"进入面试人数");

            i = 2;
            foreach (var v in values)
            {
                excel.WriteData("A"+i.ToString(), null, "'"+v.ID);
                excel.WriteData("B" + i.ToString(), null, v.Count);
                i++;
            }


            excel.SaveExcelFile();

        }

    }
}
